/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.query;

import java.io.*;

import javax.net.*;

import java.net.*;
import java.util.ArrayList;

import javax.net.ssl.*;

import nfse.*;
import nfse.result.*;

public class QueryProcessor {

    private QueryServer queryServer = null;

    private MetaDatabase mdb = null;

    public QueryProcessor(QueryServer queryServer, MetaDatabase mdb) {
        this.queryServer = queryServer;
        this.mdb = mdb;
    }

    public QueryServer getQueryServer() {
        return queryServer;
    }

    private void exitWithError(Query query, int error) {
        try {
            SocketResult sr = null;
            MarshalledResult mr = null;
            try {
                sr = (SocketResult) query.getResult();
            } catch (ClassCastException cce) {
                try {
                    mr = (MarshalledResult) query.getResult();
                } catch (ClassCastException cce2) {
                    // no op
                }
            }
            if (sr != null) {
                SocketFactory sf = null;
                if (NetFSE.USE_SSL_RESULT)
                    sf = SSLSocketFactory.getDefault();
                else
                    sf = SocketFactory.getDefault();
                Socket resultSocket = sf.createSocket(sr.host, sr.port);
                DataOutputStream resultOut = new DataOutputStream(resultSocket.getOutputStream());
                DataInputStream resultIn = new DataInputStream(resultSocket.getInputStream());

                resultOut.writeInt(-100);
                resultOut.writeInt(0);
                resultIn.readInt();
                resultOut.close();
                resultIn.close();
            } else if (mr != null) {
                SocketFactory sf = SocketFactory.getDefault();
                Socket resultSocket = sf.createSocket(mr.host, mr.port);
                DataOutputStream resultOut = new DataOutputStream(resultSocket.getOutputStream());
                DataInputStream resultIn = new DataInputStream(resultSocket.getInputStream());
                resultOut.writeInt(mr.queryID);
                resultOut.writeInt(NetFSE.RESULT_SERVER_FLAG_DONE);
                resultOut.writeInt(-100);
                resultOut.writeInt(0);
                resultIn.readInt();
                resultOut.close();
                resultIn.close();
            }
        } catch (Exception E) {
            E.printStackTrace();
        }
    }

    public int process(Query query) {
        int val = 0;
        try {
            System.out.println("Query: " + query.toXML());
            processConfig();

            Query[] subs = query.getSubqueries();
            if (subs.length > 0) {
                ResultMarshall rm = Query.marshallResults(subs, NetFSE.LOCAL_IP_ADDRESS, NetFSE.RESULT_SERVER_PORT,
                        query.getID());
                this.queryServer.getResultServer().addResultMarshall(rm);
                for (int i = 0; i < subs.length; i++) {
                    subs[i] = subs[i].detach(this.queryServer.nextQueryID());
                    // System.out.println("SUBQUERY: " + subs[i].toXML());
                    // subs[i].setID(this.queryServer.nextQueryID());
                    process(subs[i]);
                }
                System.gc();
                return 0;
            }

            int queryID = query.getID();
            Query[] queries = query.decomposeByDataType();
            
            ResultMarshall rm = null;
            if (queries.length > 1) {
                rm = Query.marshallResults(queries, NetFSE.LOCAL_IP_ADDRESS, NetFSE.RESULT_SERVER_PORT, queryID);
                this.queryServer.getResultServer().addResultMarshall(rm);
            } else {
                queries = new Query[1];
                queries[0] = query;
            }
            for (int i = 0; i < queries.length; i++) {
                int type = queries[i].getData()[0].type;
                ArrayList<SensorInfo> sensors = NetFSE.getSensorInfo();
                boolean hasSensor = false;
                for (int x = 0; x < sensors.size(); x++) {
                    if (sensors.get(x).getToolID() == type) {
                        hasSensor = true;
                        break;
                    }
                }
                if (hasSensor) {
                    NetFSERecord rec = (NetFSERecord) NetFSE.TYPE_CLASSES.get(new Integer(type));
                    if (rec != null) {
                        Query[] queries2 = new Query[2];
                        queries2[0] = queries[i].detach(this.queryServer.nextQueryID());
                        queries2[1] = queries[i].detach(this.queryServer.nextQueryID());
                        ResultMarshall rm2 = Query.marshallResults(queries2, NetFSE.LOCAL_IP_ADDRESS, NetFSE.RESULT_SERVER_PORT,
                                queryID);
                        this.queryServer.getResultServer().addResultMarshall(rm2);
                        DynamicQueryProcessor dqp = new DynamicQueryProcessor(this.queryServer);
                        dqp.process(queries2[0], mdb);
                        //HBaseSearchEngine dqp = new HBaseSearchEngine(this.queryServer);
                        //dqp.process(queries2[0], mdb);
                        StaticQueryProcessor sqp = new StaticQueryProcessor(this.queryServer, type);
                        sqp.process(queries2[1], mdb);
                    } else {
                        System.err.println("Unsupported data type: '" + NetFSE.getTypeName(type) + "'");
                        if (rm != null) {
                            rm.removeProducer();
                            rm.removeProducer();
                        }
                    }
                } else {
                    // System.err.println("No sensors for query: '" +
                    // queries[i].toXML() + "'");
                    if (rm != null) {
                        rm.removeProducer();
                        rm.removeProducer();
                    } else {
                        SocketResult sr = null;
                        MarshalledResult mr = null;
                        try {
                            sr = (SocketResult) query.getResult();
                        } catch (ClassCastException cce) {
                            try {
                                mr = (MarshalledResult) query.getResult();
                            } catch (ClassCastException cce2) {
                                // no op
                            }
                        }
                        if (sr != null) {
                            SocketFactory sf = null;
                            if (NetFSE.USE_SSL_RESULT)
                                sf = SSLSocketFactory.getDefault();
                            else
                                sf = SocketFactory.getDefault();
                            Socket resultSocket = sf.createSocket(sr.host, sr.port);
                            DataOutputStream resultOut = new DataOutputStream(resultSocket.getOutputStream());
                            DataInputStream resultIn = new DataInputStream(resultSocket.getInputStream());

                            resultOut.writeInt(-100);
                            resultOut.writeInt(0);
                            resultIn.readInt();
                            resultOut.close();
                            resultIn.close();
                        } else if (mr != null) {
                            SocketFactory sf = SocketFactory.getDefault();
                            Socket resultSocket = sf.createSocket(mr.host, mr.port);
                            DataOutputStream resultOut = new DataOutputStream(resultSocket.getOutputStream());
                            DataInputStream resultIn = new DataInputStream(resultSocket.getInputStream());
                            resultOut.writeInt(mr.queryID);
                            resultOut.writeInt(NetFSE.RESULT_SERVER_FLAG_DONE);
                            resultOut.writeInt(-100);
                            resultOut.writeInt(0);
                            resultIn.readInt();
                            resultOut.close();
                            resultIn.close();
                        }
                    }
                }
            }

        } catch (Exception E) {
            E.printStackTrace();
            exitWithError(query, val);
        }
        System.gc();
        return val;
    }

    private void processConfig() {
        try {
            File conf = new File(NetFSE.CONFIG_FILE);
            if (!conf.exists()) {
                return;
            }
            LineNumberReader in = new LineNumberReader(new FileReader(conf));
            String line = in.readLine();
            while (line != null) {
                // System.out.println(line);
                line = in.readLine();
            }
            in.close();
        } catch (Exception E) {
            E.printStackTrace();
        }
    }

    public int authenticate(Query query) {

        return 1;

    }

}